unit dbcParser;
// Database Comparer VCL v.3.0
// Copyright (C) 1998-2006, by Boris Loboda
// www.CleverComponents.com
{$I Comparer.INC}

// Base (abstract) parser for script

// History:
// 09.11.2005 (BL)
// - Parsing from stream.

interface



Uses Windows, Classes, {$IFDEF DELPHI2010}IOUtils,{$ENDIF}
     SysUtils,
     dbcCompObj, dbcClasses, dbcTypes, dbcMsgMngr,
     dbcComp_Dmn, dbcComp_Tbl, dbcComp_Viw,
     dbcDBOptions;

const // base symbol definition
  EofSy         =  0; // end of script - finish parsing
  IdentSy       =  1; // identifier
  FloatValSy    =  2; // float   const
  StrValSy      =  3; // string  const
  IntValSy      =  4; // integer const
  lParentSy     =  5; // "("
  rParentSy     =  6; // ")"
  CommaSy       =  7; // ","
  MinusSy       =  8; // -
  PlusSy        =  9; // +
  TimesSy       = 10; // *
  SlashSy       = 11; // /
  TermSy        = 12; // TERM of statement - typically ";"
  SemicolonSy   = 13; //  ";" end of operator
  EqualSy       = 14; // '='
  PointSy       = 15; // '.'
  ColonSy       = 16; // ':'
  ConcatSy      = 17; // string1 '||' strring2
  LessSy        = 18; // <
  GreaterSy     = 19; // >
  LessEqSy      = 20; // <=
  GreaterEqSy   = 21; // >=
  NotEqSy       = 22; // <> or !=
  EqEqSy        = 23; // ==
  lBracketSy    = 24; // [
  rBracketSy    = 25; // ]
  CommAtSy      = 26; // @
  BackSlashSy   = 27; // \
  Percent_Sy    = 28; // %
  AmpersandSy   = 29; // &

type

  TDebugLogOption = (dlSymbol, dlComment, dlExpr);
  TDebugLogOptions = set of TDebugLogOption;
  TScriptCodingType = (sc_Ansi, sc_Unicode, scUtf8);
  // Parse buffer: string, TFileStream, TMemoryStream
  TParseBufferType  = (pb_String, pb_Memory, pb_File);

  TResWordList = class(TStringList)
  protected
    function GetSymbol(ix: Integer): TSymbol;
    function GetSymbolByWord(aWord: string): TSymbol;
    function GetWordBySymbol(aSy: TSymbol): string;
    property Sy[ix: integer]: TSymbol read GetSymbol;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear; override;
    function AddResWord(aResWord: String; sy: TSymbol): Integer;
    property SymbolByWord[aWord: string]: TSymbol read GetSymbolByWord;
    property WordBySymbol[aSy: TSymbol]: string read GetWordBySymbol;
  end;

type
  TCustomParser = Class
  private
    fExtractor: TCustomExtract;
    fTermStr: string; // statement terminator
    fTermStrLen: Integer;
    fDatabaseType: TDatabaseType;
    fScriptCoding: TScriptCodingType;
{$IFDEF DEBUG}
    aResWordList: TResWordList;
{$ENDIF}
    procedure SetTermStr(aTerm: string);
  protected
    fUpdateProgress: Boolean;
    // string / memory / file
    fParseBuffer: TParseBufferType;
    fStringBuffer: String;
    // memory / file
    fStream: TStream;
    // current char value (from parsed string)
    ch: Char;
    fLinesCount: Integer;
    // line position (parsed string)
    Line: Integer;
    // char position into parsed string
    ChPos: Integer;
    // global position into text script buffer
    ix: integer;
    Sy: TSymbol;       // current symbol
    SyResWord: String; // current reserved word
    // symbol starting position
    SyBegPos: Integer;
    StBegPos, StEndPos: Integer; // current statement position (begin / end)
    fScriptFileName: TFileName;
    // current ident (sy = IdentSy)
    Ident: String;
    // current integer value (sy = IntValSy)
    IntVal: integer;
    // current string value (sy = StrValSy)
    StrVal: string;
    // quote char for current parsing string - ' or "
    StrQuoteCh: Char;
    // current float value (sy = FloatValSy)
    FloatVal: Double;
    // current char value (from parsed string)
    // set of database objects
    Objs: TObjs;
    // errors list
    fMsgMngr: TMsgManager;
    // reserwed words
    fResWordList: TResWordList;
    IdentCharSet: Set of AnsiChar;
    DebugLogOptions: TDebugLogOptions;
    fOnErrorMessage: TErrorMessageEvent;
    fOnLogNextLine: TLogNextLineEvent;
    fOnDebugMessage: TLogNextLineEvent;
    fOnProgressUpdate: TProgressUpdateEvent;
    fOnAddStatement: TAddStatementEvent;
    // current term stamement (string)
    property TermStr: String read fTermStr write SetTermStr;
    property TermStrLen: integer read fTermStrLen;
    procedure SetDatabaseType(aType: TDatabaseType); virtual;
    // parsed database type
    property DatabaseType: TDatabaseType read fDatabaseType write SetDatabaseType;
    function CheckTermStr(): Boolean; virtual;
    procedure DoProgressUpdate(Value, MaxValue: Integer); virtual;
    procedure DoLogNextLine(LogLine: String); virtual;
    procedure DoErrorMessage(ErrMsg: String); virtual;
    procedure DoDbgMsg(aTxt: string); virtual;
    procedure DoAddStatement(aText: String;
                             aTyp: TStatType;
                             aObjName: String;
                             aObjType: TDbObject;
                             aOperation: TDbOperation;
                             aOwnName: String;
                             var Statement: TStatement); overload; virtual;
    procedure DoAddStatement(aTyp: TStatType;
                             aObjName: String;
                             aObjType: TDbObject;
                             aOperation: TDbOperation;
                             aOwnName: String;
                             var Statement: TStatement); overload; virtual;
    // find reserwed word, related by symbol
    function ResWordBySymbol(sy: TSymbol): String; virtual;
    // add depend: d1Obj use (call) d2Obj, FldName (d2Obj) - optional
    procedure LinkDepend(d1Obj, d2Obj: TDbObj;
                         FldName: String = ''); overload;
    // add depend: d1Obj use db-object, named d2Name from d2ObjSet
    procedure LinkDepend(d1Obj: TDbObj;
                         d2Name: String;
                         d2ObjSet: TDbObjSet); overload;
    procedure AddObj(aObj: TDbObj; FreeNotAdded: Boolean = True); virtual;
    // check symbol: sy = sy1
    procedure TestSy(sy1: TSymbol); virtual;

    // test symbol and get next
    procedure TestAndGetSy(sy1: TSymbol); virtual;

    // get symbol and test sy = sy1
    procedure GetAndTestSy(sy1: TSymbol); virtual;

    // Numeric & Decimal: (Precision[, Scale]) - field declaration
    procedure GetNumDec(fData: TFldData); virtual;
    // get next char
    function GetChar(): Char; virtual;

    // forvard char [ix]
    function CurCh(): Char; virtual;
    // forvard char [ix + 1]
    function NextCh(): Char; virtual;

    // integer value
    function GetInt(): integer; virtual;
    // string value
    function GetStr(): String; virtual;
    // get next symbol
    procedure GetSy(); virtual;
    // get ident
    procedure GetIdent(); virtual;
    // extract expression: (<expr>)
    Function GetExpr(): String; virtual;
    procedure SkipLine(); virtual;
    procedure DoGetSy(); virtual;
    procedure DoBeforeGetSy(); virtual;
    procedure DoAfterGetSy(); virtual;
    function SkipText(): Boolean; virtual;
    procedure BuildResWords(); virtual;
    function IsIdent(aIdent: String): Boolean; virtual;
    procedure TestIdent(aIdent: String); virtual;
    function GetPosX(): integer;
    function GetPosY(): integer;
    function CopyTxt(PosTxt, LenTxt: integer): String;
    function LengthTxt(): Integer;
    procedure AssignTxt(aTxt: String);
    function GetDbPrefix(): String;
  public
    constructor Create(aExtractor: TCustomExtract = nil);
    destructor Destroy; override;
    property Extractor: TCustomExtract read fExtractor write fExtractor;
    property ScriptFileName: TFileName read fScriptFileName write fScriptFileName;
    property PosX: integer read GetPosX; // Pos # in script (current line)
    property PosY: integer read GetPosY; // Line # in script
    property MsgManager: TMsgManager read fMsgMngr;
    property OnErrorMessage: TErrorMessageEvent read fOnErrorMessage
                                               write fOnErrorMessage;
    property OnLogNextLine: TLogNextLineEvent read fOnLogNextLine write fOnLogNextLine;
    property OnDebugMessage: TLogNextLineEvent read fOnDEbugMessage write fOnDebugMessage;
    property OnProgressUpdate: TProgressUpdateEvent
             read fOnProgressUpdate write fOnProgressUpdate;
    property OnAddStatement: TAddStatementEvent read fOnAddStatement
                                                write fOnAddStatement;
    property db_prefix: String read GetDbPrefix;
    // parse source script into aObj
    procedure ParseScript(aScript: TStrings; aObjs: TCustomObjs); virtual;
    // parse source script from file into aObj
    procedure ParseFile(aFileName: String; aObjs: TCustomObjs); virtual;
    // DDL parse
    procedure ParseText(); virtual;
    // show / put error message
    procedure ErrMsg(msg: String); virtual;
    procedure WrnMsg(WrnStr: String);
    // additional information for ErrMsg (script name, line, pos)
    function GetScriptInfo: String; virtual;
    // find reserved word
    function FindResWord: TSymbol; virtual;
    // statement term
    function GenTerm(): String; virtual;
    // generate comment
    function GenComment(Comment: String): String; virtual;
    procedure Link_Depend(); virtual;
    property UpdateProgress: Boolean read fUpdateProgress
                                     write fUpdateProgress
                                     default True;
  end;

type
  TSelectContext = class
  public
    SaveLine: integer;
    SaveChPos: Integer;
    SaveCh: Char;
    SaveIx: Integer;
    SaveSy: TSymbol;
    SaveSyBegPos: Integer;
    SaveIdent: String;
    SelectTables:   TStrings; // "Tables" into select (table / view / procedure)
    SelectAliases:  TStrings; // Aliases (for tables) into select
    SecondPass: Boolean;
    constructor Create;
    Destructor Destroy; override;
  end;

  TCustomSQLParser = class(TCustomParser)
  private
    fConnectionOptions: TConnectionOptions;
  protected
    // parsed comment
    Comment: String;
    TempVar: TFldData;                    // temporary variable for parsing
    SelectCtx: array of TSelectContext;   // Select context stack
    SelectCtxSize: integer;               // Size of SelectCtx stack
    LocalVariables: TStringList;          // local variables into body
    procedure SetSelectContext(bm: TSelectContext);   // save position into Parsed Text
    procedure GotoSelectContext(bm: TSelectContext);  // backward to saved position
    function GetIntConst(): String;
    function SkipComment(): Boolean; virtual;
    procedure DoGetSy(); override;
    function SkipText(): Boolean; override;
    procedure SkipStatement(EndSymSet: TSymSet = [TermSy, EofSy]); virtual;
    function CopyTxtFrom(BegPos: integer): String; virtual;
    function ObjKeyName(ObjName: String; Schema: String = ''; AddDefSchema: Boolean = True): String;
    procedure AddLinkDepend(dbObj: TDbObj;        // parsed db-object
                            RefTblName: string;   // Table name
                            RefFldName: String);  // Field name
                            virtual;
  public
    constructor Create(aExtractor: TCustomExtract = nil);
    destructor Destroy; override;
    procedure ParseScript(aScript: TStrings; aObj: TCustomObjs); override;
    procedure Link_Depend(); override;
    property ConnectionOptions: TConnectionOptions read fConnectionOptions;
    function QuoteIdent(aIdent: string): string; virtual;
    procedure ParseObjBody(aObj: TDbObj); virtual;
    procedure ParseObjTxt(aObj: TDbObj); virtual;
    function ExtractToTerm(Term: array of String): String;
  end;

const
  SpaceCharSet = [' ', #9, #$0D, #$0A, #0];
  UpperLettersCharSet = ['A'..'Z'];
  LowerLettersCharSet = ['a'..'z'];
  LettersCharSet = UpperLettersCharSet + LowerLettersCharSet;
  DigitsCharSet = ['0'..'9'];

function TrimSQLText(aTxt: string): string;

function DelDblParents(expr: String): String;

implementation

//The full source code is available on purchasing the product

end.
